package com.isunland.managesystem.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import com.isunland.managesystem.R;
import com.isunland.managesystem.utils.MyDateUtil;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@SuppressWarnings({ "deprecation", "NullableProblems" }) public class BaseTimeDialogFragment
    extends DialogFragment {

  public static final String EXTRA_DATE = "com.isunland.managesystem.ui.extra_date";
  protected static final String EXTRA_START_DATE = "com.isunland.managesystem.ui.extrar_start_date";
  protected static final String EXTRA_TITLE_ID = "com.isunland.managesystem.ui.extra_title_id";
  protected static final String EXTRA_TITLE = "com.isunland.managesystem.ui.extra_title";
  private static final String CHOOSE_TIME = "选择时间";
  private static final String CHOOSE_DATE = "选择日期";

  private Date mStartDate;
  private AlertDialog mAlertDialog;
  private Date mDate;
  private TimePicker timePicker;
  private Button c;
  private DatePicker datePicker;
  private String mTitle;
  private CallBack mCallBack;

  /**
   * 创建日期Dialog
   *
   * @param startDate 显示的日期
   * @param titleId Dialog标题的id.
   */
  private static BaseTimeDialogFragment newInstance(Date startDate, int titleId, String title) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_START_DATE, startDate);
    if (titleId != 0) {

      args.putInt(EXTRA_TITLE_ID, titleId);
    }
    if (title != null) {

      args.putString(EXTRA_TITLE, title);
    }
    BaseTimeDialogFragment fragment = new BaseTimeDialogFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static BaseTimeDialogFragment newInstance(Date startDate, int titleId) {
    return newInstance(startDate, titleId, null);
  }

  public static BaseTimeDialogFragment newInstance(Date startDate, String title) {
    return newInstance(startDate, 0, title);
  }

  public static BaseTimeDialogFragment newInstance(Date startDate) {
    return newInstance(startDate, 0, null);
  }

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    // 初始化DatePickerTimePicker
    mStartDate = (Date) getArguments().getSerializable(EXTRA_START_DATE);
    if (mStartDate == null) {
      mStartDate = new Date();
    }
    mTitle = initTitle();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(mStartDate);
    int year = calendar.get(Calendar.YEAR);
    final int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_choose_time, null);

    datePicker = (DatePicker) v.findViewById(R.id.dp_date_chooseTimeDialogFragment);
    //        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
    //            @Override
    //            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    //                sv.fullScroll(ScrollView.FOCUS_DOWN);
    //            }
    //        });
    datePicker.init(year, month, day, null);
    timePicker = (TimePicker) v.findViewById(R.id.tp_time_chooseTimeDialogFragment);
    timePicker.setIs24HourView(true);
    timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
    timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));

    // 初始化Dialog
    mAlertDialog = new AlertDialog.Builder(getActivity()).setTitle(mTitle)
        .setView(v)
        .setPositiveButton(android.R.string.ok, null)
        .setNegativeButton(android.R.string.cancel, null)
        .setNeutralButton(CHOOSE_TIME, null)
        .create();

    mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {

      @Override public void onShow(DialogInterface dialog) {

        Button b = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        b.setOnClickListener(new View.OnClickListener() {

          @Override public void onClick(View view) {

            mDate = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
                timePicker.getCurrentMinute(), 0).getTime();

            // 如果有条件判断.在方法里面调用setResult()处理,不走下面的setResult方法;
            // 这段代码默认不执行.
            boolean isNeed = condition(mDate, mStartDate);
            if (isNeed) {
              return;
            }
            setResult(Activity.RESULT_OK);
          }
        });

        c = mAlertDialog.getButton(AlertDialog.BUTTON_NEUTRAL);
        c.setOnClickListener(new View.OnClickListener() {

          @Override public void onClick(View view) {
            mDate = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(),
                datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
                timePicker.getCurrentMinute(), 0).getTime();
            changeType();
          }
        });
      }
    });
    return mAlertDialog;
  }

  private void changeType() {

    //如果是显示“选择日期”的时候，却换到选择时间，
    String chooseType = c.getText().toString();
    if (chooseType.equals(CHOOSE_DATE)) {
      datePicker.setVisibility(View.VISIBLE);
      timePicker.setVisibility(View.INVISIBLE);
      mAlertDialog.setTitle(mTitle);
      c.setText(CHOOSE_TIME);
    }
    if (chooseType.equals(CHOOSE_TIME)) {

      datePicker.setVisibility(View.INVISIBLE);
      timePicker.setVisibility(View.VISIBLE);
      mAlertDialog.setTitle(MyDateUtil.dateToString(mDate, MyDateUtil.TYPE_DATE5));
      c.setText(CHOOSE_DATE);
    }
  }

  /**
   *
   */
  private String initTitle() {
    String titleFinal = null;
    int titleId = getArguments().getInt(EXTRA_TITLE_ID);
    String title = getArguments().getString(EXTRA_TITLE);
    if (title != null) {
      titleFinal = title;
    } else {
      try {
        titleFinal = getString(titleId);
      } catch (Exception e) {
        // Auto-generated catch block
        e.printStackTrace();
      }
    }
    if (TextUtils.isEmpty(titleFinal)) {
      titleFinal = "请选择时间";
    }
    return titleFinal;
  }

  /**
   * 日期格式判断.需要自己实现判断日期判断代码.
   *
   * .
   * .
   *
   * @return 是否需要条件.false代表不需要, true代表需要判断.
   */
  public boolean condition(Date mDate, Date mStartDate) {
    return false;
  }

  /**
   * 将用户选择的日期返回.
   */
  protected void setResult(int resultCode) {
    if (mCallBack != null) mCallBack.select(mDate);
    if (getTargetFragment() == null) return;
    Intent i = new Intent();
    i.putExtra(EXTRA_DATE, mDate);
    getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);
    mAlertDialog.dismiss();
  }

  public BaseTimeDialogFragment setCallBack(CallBack callBack) {
    mCallBack = callBack;
    return this;
  }

  public interface CallBack {
    void select(Date date);
  }
}
